package Game.Buff;

import java.util.ArrayList;
import java.util.List;

import org.newdawn.slick.SlickException;

import Game.Objects.GameObject;

/** Buff Manager class
 * @author Aikidos
 */
public class BuffManager {
	
	/** Owner */
	private GameObject _owner;
	
	/** List of buff */
	private List<BuffBase> _lstBuff = new ArrayList<BuffBase>();
	
	/** List of removed buff */
	private List<BuffBase> _lstRemovedBuff = new ArrayList<BuffBase>();
	
	public BuffManager(GameObject owner) {
		_owner = owner;
	}
	
	/** Returns owner
	 * @return Owner
	 */
	public GameObject getOwner() {
		return _owner;
	}
	
	/** Returns list of buff
	 * @return List of buff
	 */
	public List<BuffBase> getList() {
		return _lstBuff;
	}
	
	/** Returns buff by class name
	 * @param className - Class name
	 * @return Buff
	 */
	public BuffBase getBuffByClass(String className) {
		for (BuffBase buff : _lstBuff) {
			if (buff.getClass().getName() == className) return buff;
		}
		
		return null;
	}

	/** Returns true if buff is removed
	 * @param buff - Buff
	 * @return True if buff is removed
	 */
	public boolean isRemoved(BuffBase buff) {
		return _lstRemovedBuff.contains(buff);
	}
	
	/** Add buff to manager
	 * @param buff - Buff
	 */
	public void addBuff(BuffBase buff) throws SlickException {
		// Remove old buff
		for (BuffBase buffBase : _lstBuff) {
			if (buffBase.getClass().getName() == buff.getClass().getName()) {
				remove(buffBase);
			}
		}
		
		_lstBuff.add(buff);
		buff.init();
	}
	
	/** Remove buff
	 * @param buff - Buff
	 */
	public void remove(BuffBase buff) throws SlickException {
		if (buff.getBuffManager() == this)
			_lstRemovedBuff.add(buff);
	}
	
	public void update(int delta) throws SlickException {
		// Update buff
		for (BuffBase buff : _lstBuff) {
			buff.update(delta);
		}
	}
	
	public void step() throws SlickException {
		// Step buff
		for (int  i = 0; i < _lstBuff.size(); i++) {
			if (!_lstRemovedBuff.contains(_lstBuff.get(i))) {
				_lstBuff.get(i).step();
				_lstBuff.get(i).subSteps(1);
			
				if (!_lstBuff.get(i).isUnlimited() && 
						(_lstBuff.get(i).getNumOfSteps() <= 0)) remove(_lstBuff.get(i));
			}
		}
		
		// Clear
		for (int  i = 0; i < _lstBuff.size(); i++) {
			for (int j = 0; j < _lstRemovedBuff.size(); j++) {
				if (_lstBuff.get(i) == _lstRemovedBuff.get(j)) {
					_lstBuff.get(i).shutdown();
					_lstBuff.remove(i);
					
					i = 0;
					break;
				}
			}
		}
		
		_lstRemovedBuff.clear();
	}

}
